package org.xxpay.pay.channel.alizftpay;

import com.alipay.api.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.exception.ServiceException;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.core.entity.PayPassageAccount;
import org.xxpay.pay.channel.PayConfig;
import org.xxpay.pay.channel.alipay.AlipayConfig;
import org.xxpay.pay.ctrl.common.BaseController;
import org.xxpay.pay.service.CommonService;

import java.io.File;

/**
 * @author: dingzhiwei
 * @date: 2020/11/1
 * @description:
 */
@Service
public class BaseApiService extends BaseController {

    /** 当前线程变量，用于判断当前是否是测试状态
     由于getPayParam()函数中判断了子账号的状态, 当MS新增后状态是非开启，也需要进行接口验证，所以添加该线程变量；
     另外商户下单时前置判断条件已经验证了该账号状态，此时判断状态感觉有点重复（需确认）；
     **/
    public static final ThreadLocal<String> IS_TEST_FLAG = new ThreadLocal<>();

    @Autowired
    public PayConfig payConfig;

    @Autowired
    public CommonService commonService;

    private static final MyLog _log = MyLog.getLog(BaseApiService.class);

    /** 获取支付宝接口调用类 **/
    public DefaultAlipayClient getAlipayClient(AlizftpayConfig alizftpayConfig) throws AlipayApiException {


        if("cert".equals(alizftpayConfig.getEncryptionType())){ //证书加密方式
            CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
            certAlipayRequest.setServerUrl(AlizftpayConfig.ALIPAY_GATEWAY_URL);
            certAlipayRequest.setAppId(alizftpayConfig.getAppId());
            certAlipayRequest.setPrivateKey(alizftpayConfig.getPrivateKey());
            certAlipayRequest.setFormat(AlipayConfig.FORMAT);
            certAlipayRequest.setCharset(AlipayConfig.CHARSET);
            certAlipayRequest.setSignType(AlipayConfig.SIGNTYPE);

            certAlipayRequest.setCertPath(payConfig.getCertRootPath() + File.separator + alizftpayConfig.getAppPublicCert());
            certAlipayRequest.setAlipayPublicCertPath(payConfig.getCertRootPath() + File.separator + alizftpayConfig.getAlipayPublicCert());
            certAlipayRequest.setRootCertPath(payConfig.getCertRootPath() + File.separator + alizftpayConfig.getAlipayRootCert());
            return new DefaultAlipayClient(certAlipayRequest);

        }else{ //key 或者 空都为默认普通加密方式

            return new DefaultAlipayClient(AlizftpayConfig.ALIPAY_GATEWAY_URL, alizftpayConfig.getAppId(),
                    alizftpayConfig.getPrivateKey(), AlipayConfig.FORMAT, AlipayConfig.CHARSET,
                    alizftpayConfig.getAlipayPublicKey(), AlipayConfig.SIGNTYPE);
        }
    }

    /** 封装支付宝接口调用函数 **/
    public <T extends AlipayResponse> T alipayExecute(AlizftpayConfig alizftpayConfig, AlipayRequest<T> request) throws AlipayApiException {

        if("cert".equals(alizftpayConfig.getEncryptionType())){ //证书加密方式
            return getAlipayClient(alizftpayConfig).certificateExecute(request);

        }else{ //key 或者 空都为默认普通加密方式
            return getAlipayClient(alizftpayConfig).execute(request);
        }
    }

    /**
     * 获取三方支付配置信息
     * 如果是平台账户,则使用平台对应的配置,否则使用商户自己配置的渠道
     * @param payOrder
     * @return
     */
    public String getPayParam(PayOrder payOrder) {
        String payParam = "";
        PayPassageAccount payPassageAccount = commonService.payPassageAccountService.findById(payOrder.getPassageAccountId());

        if(payPassageAccount == null) throw new ServiceException(RetEnum.RET_MGR_PAY_PASSAGE_ACCOUNT_NOT_EXIST);
        if(StringUtils.isBlank(IS_TEST_FLAG.get()) && payPassageAccount.getStatus() != MchConstant.PUB_YES){ // 空=非测试，需要判断状态是否开启
            throw new ServiceException(RetEnum.RET_MGR_PAY_PASSAGE_ACCOUNT_NOT_EXIST);
        }
        payParam = payPassageAccount.getParam();
        if(StringUtils.isBlank(payParam)) throw new ServiceException(RetEnum.RET_MGR_PAY_PASSAGE_ACCOUNT_NOT_EXIST); //仍然为空，说明配置有误
        return payParam;
    }

}
